/*
 * @Author: luoyunhai
 * @Date: 2020-01-14  15:32:52.91
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-07-29 15:51:41
 * @Description: 司机端运单详情
 */

import React, { Component } from 'react';
import {
  Image, Linking, NativeModules,
  SafeAreaView,
  ScrollView,
  StyleSheet,
  Text,
  TouchableOpacity,
  View
} from 'react-native';
import {
  fontColorCoffee,
  fontColorSecDeepGray,
  mainBgColorLightGray,
  mainBgColorWhite,
  px2dp,
  splitLineColorLightGray,
  fontColorDeepRed,
  fontColorLightGreen,
} from '@/styles';
import { msg } from '@/common';
import supply from '@/api/supply';
import { iconPhoneNew } from '@/images';
import { getDistance } from '@/common/util';
import { fetchUnitList } from '@/api/source-release';
import baseConfig from '@/config/baseConfig';
import ImageViewer from '../../../components/XmImageViewer';
import WaybillLine from '../../../components/waybill-line';
import DriverInfoCard from '../../../components/driverInfo-card';
import TypeAssemble from '../../../components/type-assemble';

const { fileUrl } = baseConfig;

export default class WaybillDetails extends Component {
  constructor(props) {
    super(props);
    this.state = {
      details: null,
      modalVisible: false,
      imageSources: [],
      unitOptionsObj: [],
      truckTypeDict: [],
      unitList: [],
      plat: '' // 1  货主端   2车主端  3 司机端
    };
  }

  componentDidMount() {
    const { navigation } = this.props;
    const state = navigation.state || {};
    const params = state.params || {};
    const { businessNo, plat, } = params;
    this.setState({ plat });
    this.fetchUnitList();
    this.getUnitList().then(() => {
      this.info(businessNo, plat);
    });
  }

  render() {
    const { details, modalVisible, imageSources, plat } = this.state;
    return (
      <SafeAreaView style={style.container}>
        <ScrollView style={[plat == 3 ? style.scrollMargin : '']}>
          {details && (
            <View>
              {/* plat   1  货主端   2车主端  3 司机端 */}
              {this.waybillView()}
              {/* 货物类型 */}
              {this.goodsTypeView()}
              {/* 运费 */}
              {this.waybillCostView()}
              {/* 备注信息 */}
              {this.remakeView()}
              {/* 装卸信息 */}
              {this.waybillRouteView()}
              {/* 司机信息 */}
              {this.driverInfo()}
              {/* 车辆信息 */}
              {this.vehicleInfo()}
              {/* 货主信息 */}
              {this.cargOwnerInfo()}
              {/* 回单信息 */}
              {this.receiptInfoView()}
              {/* 图片查看 */}
              <ImageViewer
                leftBackIcon={require('../../../images/icons/back_white.png')}
                showViewModal={() => this.setState({ modalVisible: false })}
                previewModal={modalVisible}
                images={imageSources}
              />
            </View>
          )}
        </ScrollView>
      </SafeAreaView>
    );
  }

  // 获取单位
  getUnitList = () => {
    return new Promise((resolve) => {
      supply.unitList().then(res => {
        this.setState({ unitList: res.data }, () => {
          resolve(res);
        });
      });
    });
  }

  // 转义单位
  matchingUnit(unit) {
    const { unitList } = this.state;
    if (!unit || unitList.length === 0) {
      return '';
    }
    if (unitList.length > 0) {
      const unitName = unitList.filter(u => u.code === unit);
      if (unitName.length > 0) {
        return unitName[0].name;
      }
      return unit;
    }
    return unit;
  }

  // 详情跳转回单
  toReceipt() {
    const { details, plat } = this.state;
    if (plat === 3 && details.transportStatus === 1) {
      // 装货、卸货回单上传
      supply.getUploadTick({ transportNo: details.transports[0].transportNo }).then(res => {
        msg.emit('router: goToNext', {
          routeName: 'ReceiptUpload',
          routerFrom: 'DriverWayOrder',
          data: details,
          transportNo: details.transports[0].transportNo,
          guideData: res.data
        });
      });
    } else {
      // 回单编辑
      msg.emit('router: goToNext', {
        routeName: 'ReceiptEdit',
        routerFrom: 'DriverWayOrder',
        data: details,
        transportNo: details.transports[0].transportNo
      });
    }
  }

  // 头部
  itemHead = (text) => {
    return (
      <View style={style.itemHead}>
        <Text style={{ color: '#333232', fontSize: px2dp(32) }}>{text}</Text>
      </View>
    );
  }

  checkStatus = () => {
    // 1  货主端   2车主端  3 司机端
    let { plat } = this.state;
    let { status, transportStatus } = this.state.details;
    let state = {};
    if (plat === 2 || plat === 3) {
      // transportStatus = {
      //   1: <Text style={{color: fontColorDeepRed}}>未完成</Text>,
      //   2: <Text style={{color: fontColorSecDeepGray}}>已完成</Text>,
      // }
      state = {
        1: <Text style={{ color: fontColorDeepRed }}>未完成</Text>,
        2: <Text style={{ color: fontColorDeepRed }}>未完成</Text>,
        3: <Text style={{ color: fontColorSecDeepGray }}>已完成</Text>,
        4: <Text style={{ color: fontColorSecDeepGray }}>已完成</Text>,
      };
    } else if (plat === 1) {
      state = {
        1: <Text style={{ color: fontColorDeepRed }}>贷装货</Text>,
        2: <Text style={{ color: fontColorCoffee }}>运输中</Text>,
        3: <Text style={{ color: fontColorLightGreen }}>已送达</Text>,
        4: <Text style={{ color: fontColorSecDeepGray }}>已完成</Text>,
        5: <Text style={{ color: fontColorSecDeepGray }}>已取消</Text>,
      };
    }
    return state[status];
  }

  // 运单
  waybillView = () => {
    // 1  货主端   2车主端  3 司机端
    const { details, plat } = this.state;
    const { waybillNo, state, freightConsignorPer, freightUnit, } = details;
    return (
      <View style={[style.itemFrame, style.waybill]}>
        <View style={style.waybillHead}>
          <Text
            style={{
              color: '#9D9A95',
              fontSize: px2dp(24)
            }}
          >
            {`运单号：${waybillNo}`}
          </Text>
          {this.checkStatus()}
        </View>
        <View style={{ marginTop: px2dp(20) }}>
          <Text style={{ color: '#333232' }}>
            <Text style={{ fontSize: px2dp(28) }}>运费： </Text>
            <Text style={{ fontSize: px2dp(24), fontWeight: 'bold' }}>￥</Text>
            <Text style={{ fontSize: px2dp(36), fontWeight: 'bold' }}>{`${freightConsignorPer}`}</Text>
            <Text style={{ fontSize: px2dp(28), fontWeight: 'bold' }}>
              /
              {this.matchingUnit(freightUnit)}
            </Text>
          </Text>
        </View>
      </View>
    );
  }

  // 货物类型
  goodsTypeView = () => {
    const { details, unitOptionsObj } = this.state;
    const { goodsName, packageName, weight, weightUnit } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('货物类型')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble
            lineData={[goodsName, packageName, `${weight}${unitOptionsObj[weightUnit]}`]}
          />
        </View>
      </View>
    );
  }

  // 运费
  waybillCostView = () => {
    const { details } = this.state;
    const { freightConsignorPer, freightUnit, lossesAmount, lossesUnit } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('运费')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble
            lineData={[`运费：${freightConsignorPer}元/${this.matchingUnit(freightUnit)}`, `损耗费：${lossesAmount}元/${this.matchingUnit(lossesUnit)}`]}
          />
        </View>
      </View>
    );
  }

  // 备注
  remakeView = () => {
    const { details } = this.state;
    const { transports } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('备注信息')}
        <View style={{ marginTop: px2dp(20) }}>
          <TypeAssemble
            lineData={[transports[0].remark]}
          />
        </View>
      </View>
    );
  }

  // 装卸信息
  waybillRouteView = () => {
    const { details } = this.state;
    const { roads } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('装卸信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {
            roads.map((r, index, arr) => {
              return (
                <WaybillLine
                  key={r.id}
                  sources={r}
                  renderInfoItem={this._renderInfoItem}
                  lineHeight={150}
                  type={r.type}
                  lineText={this.computeDistance(index, arr)}
                  lineIsShow={index < roads.length - 1}
                />
              );
            })
          }
        </View>
      </View>
    );
  }

  _renderInfoItem = (item) => {
    const {
      type,
      province,
      addressDetails,
      city,
      district,
      linkMan,
      linkMobile,
      loadingEndTime,
      loadingStartTime,
    } = item;
    return (
      <View style={{ marginLeft: px2dp(20) }}>
        <View style={{ flexDirection: 'row', justifyContent: 'space-between' }}>
          <View style={{ flex: 1 }}>
            <Text
              style={{
                color: '#343332',
                fontSize: px2dp(32)
              }}
              numberOfLines={2}
              ellipsizeMode='tail'
            >
              {`${province}${city}${district}${addressDetails}`}
            </Text>
          </View>
          {
            (linkMobile != null && linkMobile != '') && (
              <TouchableOpacity
                onPress={() => this.handleFunc(linkMobile)}
              >
                <Image
                  style={{
                    width: px2dp(69),
                    height: px2dp(69),
                  }}
                  source={iconPhoneNew}
                  resizeMode='stretch'
                />
              </TouchableOpacity>
            )
          }

        </View>
        {
          (linkMan != null && linkMan != '') && (
            <Text
              style={{
                marginTop: px2dp(10),
                color: '#666562',
                fontSize: px2dp(26)
              }}
            >
              {`联系人：${linkMan}`}
            </Text>
          )
        }
        {
          type === 1 && (
            <Text
              style={{
                marginTop: px2dp(10),
                color: '#666562',
                fontSize: px2dp(26)
              }}
            >
              {`${loadingStartTime} - ${loadingEndTime} 可装货`}
            </Text>
          )
        }
      </View>
    );
  }

  // 司机信息
  driverInfo = () => {
    const { details } = this.state;
    const { cars, drivers } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('司机信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {
            drivers.map(v => {
              return (
                <TouchableOpacity
                  key={v.id}
                  onPress={() => this.getDriverDetail(v.driverId)}
                >
                  <DriverInfoCard
                    isRight
                    type={1}
                    imgUrl={v.head}
                    name={v.name}
                    info={v}
                  />
                </TouchableOpacity>
              );
            })
          }
        </View>
      </View>
    );
  }

  // 车辆信息
  vehicleInfo = () => {
    const { details } = this.state;
    const { cars } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('车辆信息')}
        <View style={{ marginTop: px2dp(20) }}>
          {
            cars.map(v => {
              return (
                <TouchableOpacity
                  key={v.carNo}
                  onPress={() => this.carInfo(v.carId)}
                >
                  <DriverInfoCard
                    type={2}
                    imgUrl={v.head}
                    name={v.carNo}
                    info={v}
                  />
                </TouchableOpacity>
              );
            })
          }
        </View>
      </View>
    );
  }

  // 货主信息
  cargOwnerInfo = () => {
    const { details } = this.state;
    const { supplyOwnerResponse, orderId } = details;
    return (
      <View style={style.itemFrame}>
        {this.itemHead('货主信息')}
        <View style={{ marginTop: px2dp(20) }}>
          <TouchableOpacity
            onPress={() => this.getSourceDetail(supplyOwnerResponse.custId, orderId)}
          >
            <DriverInfoCard
              isRight
              type={1}
              imgUrl={supplyOwnerResponse.head}
              name={supplyOwnerResponse.name}
              info={supplyOwnerResponse}
            />
          </TouchableOpacity>
        </View>
      </View>
    );
  }

  // 回单信息
  receiptInfoView = () => {
    const { details, imageSources } = this.state;
    const { ticks } = details;
    let images = ticks.filter(item => item.fileUrl !== null);
    return (
      <View style={style.itemFrame}>
        {this.itemHead('回单信息')}
        <TouchableOpacity
          onPress={() => {
            if (imageSources.length > 0) {
              this.setState({ modalVisible: true });
            }
          }}
          style={style.receiptContainer}
        >
          <View style={{ flexDirection: 'row' }}>
            {
              (images.length > 0) ? (
                ticks.map(item => {
                  return (
                    <Image
                      key={item.id}
                      style={{
                        width: px2dp(120),
                        height: px2dp(120),
                        marginRight: px2dp(20)
                      }}
                      source={{ uri: fileUrl + item.fileUrl }}
                      resizeMode='stretch'
                    />
                  );
                })
              ) : (
                <View
                  style={{
                    height: px2dp(120),
                    justifyContent: 'center',
                  }}
                >
                  <Text style={{ textAlign: 'center' }}>暂无回单信息</Text>
                </View>
              )
            }
          </View>
          {/* <Image
            style={{
              width: px2dp(24),
              height: px2dp(24),
            }}
            source={require('../../../../image/wl/icon_right_gray.png')}
            resizeMode='stretch'
          /> */}
        </TouchableOpacity>
      </View>
    );
  }

  // 计算距离
  computeDistance(index, arr) {
    if (index === (arr.length - 1)) {
      return;
    }
    let distance = getDistance(arr[index].lat, arr[index].lgt, arr[index + 1].lat, arr[index + 1].lgt);
    return `${distance} km`;
  }

  handleFunc = (phone) => {
    if (!phone) return msg.emit('app:tip', { text: '联系电话无效' });
    const url = `tel:${phone}`;
    Linking.canOpenURL(url)
      .then((supported) => {
        if (!supported) {
          NativeModules.WindowModule.showWindow({
            content: `您的设备不支持该功能，请手动拨打${phone}`,
            onlyRightBtn: '1'
          }, (e) => {
          });
          return;
        }
        return Linking.openURL(url);
      })
      .catch((err) => {
        msg.emit('app:tip', { text: err });
      });
  }

  /**
   * 接口调用
   * @param businessNo
   */

  // 查询运单详情
  info = (businessNo, plat) => {
    supply.info({ businessNo, plat }).then(res => {
      if (res.success) {
        const { ticks } = res.data;
        let newImageSources = [];
        if (ticks.length > 0) {
          ticks.forEach(image => {
            newImageSources.push({
              url: image.fileUrl,
              adress: image.addr,
              type: image.type === 1 ? '装货单' : '卸货单',
            });
          });
        }
        this.setState({ imageSources: newImageSources });
        this.setState({ details: res.data });
      } else {
        msg.emit('router: back');
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 获取司机详情
  getDriverDetail = (driverId) => {
    supply.driverInfo({ driverId }).then(res => {
      if (res.success) {
        let data = {
          head: res.data.head ? res.data.head : null,
          name: res.data.name,
          mobile: res.data.mobile,
          joinTime: res.data.joinTime,
          driverAge: res.data.driverAge,
          waybillCount: res.data.waybillCount,
        };
        msg.emit('router: goToNext', {
          routeName: 'DriverDetail',
          data: data,
          isDriver: true
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 获取货主详情
  getSourceDetail = (custId, orderId) => {
    supply.consignorDetail({ custId, orderId }).then(res => {
      console.log(res);
      if (res.success) {
        msg.emit('router: goToNext', {
          routeName: 'DetailDriverDetail',
          data: res.data
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  // 获取车辆详情
  carInfo = (id) => {
    supply.getCarinfo({ id }).then(res => {
      if (res.success) {
        let infoData = {
          vehiclePhoto: '',
          numberPlates: res.data.carNo, // 车牌号
          joinTime: res.data.createTime, // 入住时间
          driveAge: res.data.age, // 驾龄
          vehicleModel: res.data.carType, // 车型
          vehicleLong: res.data.vehicleLength, // 车长
          load: res.data.vehicleTonnage, // 载重
          ascriptionEnterprise: res.data.legalName, // 所属企业
          cooperateType: res.data.vehicleCoopType, // 合作类型
          obdStatus: res.data.obdStatus, // obd信息
          obdInfo: res.data.obdInfo, // obd信息
          vehicleEquipment: '', // 车载设备
        };
        msg.emit('router: goToNext', {
          routeName: 'VehicleInfo',
          infoData,
        });
      } else {
        msg.emit('app:tip', { text: res.msg });
      }
    });
  }

  swtichCooperateType=(key) => {
    switch (key) {
    case '1':
      return '自营';
    case '2':
      return '加盟';
    case '3':
      return '挂靠';
    case '4':
      return '社会车辆';
    default:
      return '-';
    }
  }

  // 获取单位列表
  fetchUnitList = (status) => {
    fetchUnitList({ status }).then((res) => {
      if (res.success) {
        let unitOptionsObj = {};
        res.data.forEach(item => {
          unitOptionsObj[item.code] = item.name;
        });
        this.setState({ unitOptionsObj });
      } else {
        msg.emit('app:tip', { text: '遇到网络错误，请重试' });
      }
    });
  };
}
const style = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: mainBgColorLightGray,
    padding: px2dp(20)
  },
  scrollMargin: {
    marginBottom: px2dp(150)
  },
  itemFrame: {
    marginBottom: px2dp(20),
    borderRadius: px2dp(16),
    backgroundColor: mainBgColorWhite,
    padding: px2dp(20)
  },
  waybill: {
    paddingTop: px2dp(30),
    paddingBottom: px2dp(30)
  },
  waybillHead: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center'
  },
  goodsInfo: {
    marginTop: px2dp(20),
  },
  itemHead: {
    justifyContent: 'center',
    paddingBottom: px2dp(15),
    borderBottomWidth: px2dp(1),
    borderBottomColor: splitLineColorLightGray
  },
  receiptContainer: {
    marginTop: px2dp(20),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
});
